#!/bin/bash
#
# Copyright 2011 Google Inc. All Rights Reserved.
# Author: sdd@google.com (Salvatore Domenick Desiano)
#
# Create a checkout of the GLP repository, including secondary clones and
# infrastructure required for Rietveld code reviews. See glp-common.sh for more
# information on the development process used by GLP developers.

# Read parameters and initialize variables.
source "$(dirname "$0")/glp-common.sh"
declare -r new_checkout_root="${1}"
declare -r new_edit_name="${2}"
if [[ -z "${new_checkout_root}" || -z "${new_edit_name}" ]]; then
  glp::die "usage: $0 new_checkout_root edit_clone_name";
elif [[ -e "${new_checkout_root}" ]]; then
  glp::die "refusing to overwrite ${new_checkout_root}"
fi
glp::initialize_checkout_variables "${new_edit_name}" "${new_checkout_root}"

# Calculate paths for new checkout.
declare -r new_review_root="${new_checkout_root}/review"
declare -r new_checkout_rc="${new_checkout_root}/glp.checkout.rc"
declare -r new_rietveld_upload_script="${new_review_root}/upload.py"

echo "Creating a checkout at ${new_checkout_root} with edit clone \
${new_edit_name}..."
echo '  creating checkout root...'
glp::mkdir_or_die "${new_checkout_root}"

echo "  creating review root at ${new_review_root}..."
glp::mkdir_or_die "${new_review_root}"

echo "  caching upstream repository in ${UPSTREAM_CLONE}..."
hg clone --quiet "${HG_URL}" "${UPSTREAM_CLONE}" || glp::die 'failed.'

echo "  creating ${new_checkout_rc}..."
cp "${SCRIPT_DIR}/glp.checkout.template.rc" "${new_checkout_rc}" || \
  glp::die 'failed.'

echo "  retrieving upload script into ${new_rietveld_upload_script}..."
curl --silent --show-error --output "${new_rietveld_upload_script}" \
  "${RIETVELD_URL}/static/upload.py" || glp::die 'failed.'
chmod a+x "${new_rietveld_upload_script}" || glp::die 'failed.'

# Create the first edit clone.
glp::cd_or_die "${new_checkout_root}"
"${SCRIPT_DIR}/glp-clone" "${new_edit_name}"
glp::cd_oldpath_or_die "${new_checkout_root}"

echo "Checkout created in ${new_checkout_root} including edit clone \
${new_edit_name}."
